package com.iwuyc.tools.commons.codec.type;

import com.iwuyc.tools.commons.codec.Codec;
import com.iwuyc.tools.commons.codec.TypeEnum;
import com.iwuyc.tools.commons.exception.IllegalFormatException;
import com.iwuyc.tools.commons.util.collection.ArrayUtil;
import com.iwuyc.tools.commons.util.math.NumberUtils;

import java.util.Arrays;

public class ShortCodec implements Codec<Short> {
    @Override
    public Short decode(byte[] data) {
        int dataLen = ArrayUtil.arrayLength(data);
        if (dataLen != 5) {
            throw new IllegalFormatException("data长度必须为5");
        }
        byte flags = data[0];
        if (TypeEnum.SHORT.getFlags() != flags) {
            throw new IllegalFormatException("data类型标识必须为" + TypeEnum.SHORT.getFlags());
        }
        return NumberUtils.toShort(Arrays.copyOfRange(data, 1,3));
    }

    @Override
    public byte[] encode(Short data) {
        if (null == data) {
            throw new IllegalFormatException("data不允许为null");
        }
        final byte[] bytes = NumberUtils.toBytes(data);

        final byte[] result = new byte[5];
        result[0] = TypeEnum.SHORT.getFlags();
        System.arraycopy(bytes, 0, result, 1, bytes.length);
        return result;
    }

    @Override
    public TypeEnum[] supportedTypes() {
        return new TypeEnum[]{TypeEnum.SHORT};
    }
}
